package study;

import static java.lang.System.out;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

class StartRMIRegistry {

	public static void main(String[] args) {
		/*
		 * if (System.getSecurityManager() == null) {
		 * System.setSecurityManager(new SecurityManager()); }
		 */

		out.println("start locale RMI Registry on 1099");
		try {
			Registry registry = LocateRegistry.createRegistry(1099);
			//Registry registry = LocateRegistry.getRegistry("192.168.0.106");
			SayHelloServer remoteObj = new SayHelloServer();

			registry.rebind("test", remoteObj);

			
			out.println("---Remote Objects---");
			for (String eachName : registry.list()) {
				Remote o = registry.lookup(eachName);
				out.println(eachName+"->"+o);
			}

			out.println();
			
			
			dumpAllThread();
			
			out.println("call sayHello() of the 'test' Remote Object");
			Remote stub = registry.lookup("test");
			Method method = stub.getClass().getMethod("catSayHello");
			method.invoke(stub);

			Method method2 = stub.getClass().getMethod("dogSayHello");
			method2.invoke(stub);
			

			Thread.sleep(1000000);
			
		} catch (Exception e) {

			e.printStackTrace();
		}

	}
	public static void dumpAllThread(){
		Thread[] threads = findAllThreads();
		out.println("---all threads ("+threads.length+")---");		
		for(Thread t:threads){
			out.println(t.getName()+"\t\t"+t.getThreadGroup().getName()+"\t"+t.getPriority()+"\t"+t.isAlive()+"\t"+t.isDaemon());
		}
		out.println();
	}
	public static Thread[] findAllThreads() {
		ThreadGroup group = Thread.currentThread().getThreadGroup();
		ThreadGroup topGroup = group;
		// traverse the ThreadGroup tree to the top
		while (group != null) {
			topGroup = group;
			group = group.getParent();
		}
		// Create a destination array that is about
		// twice as big as needed to be very confident
		// that none are clipped.
		int estimatedSize = topGroup.activeCount() * 2;
		Thread[] slackList = new Thread[estimatedSize];
		// Load the thread references into the oversized
		// array. The actual number of threads loaded
		// is returned.
		int actualSize = topGroup.enumerate(slackList);
		// copy into a list that is the exact size
		Thread[] list = new Thread[actualSize];
		System.arraycopy(slackList, 0, list, 0, actualSize);
		return list;
	}
}


